package com.tgh.help;

import java.util.ArrayList;
import java.util.List;

import javax.crypto.spec.IvParameterSpec;

import android.app.TabActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
/**
 * 用来显示上传中文件的fragment
 * @author tiangh
 * 2012-4-27 下午4:52:23
 */
public class UploadingFragment extends Fragment {
	
	
	private ViewPager viewPager;
	private final static List<Record> records=new ArrayList<Record>();
	
	private final static Double SINGLE_PAGE_ITEMS=7.00;
	private static int totalPages;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.fragment_uploading, null);
		viewPager = (ViewPager) root.findViewById(R.id.pager_uploading);
		//这是生成测试数据
		records.clear();
		records.addAll(Generator.genRecords(50));
		totalPages=computeTotalPage(records.size());
		
		viewPager.setAdapter(new UploadingAdapter(getFragmentManager()));
		return root;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}
	
	/**
	 * 真正使用时，一定要通过该方法来设置数据
	 * @param initRecords
	 */
	public void setRecords(List<Record> initRecords) {
		if (initRecords!=null) {
			records.clear();
			records.addAll(initRecords);
			totalPages=computeTotalPage(records.size());
		}
	}
	
	public int computeTotalPage(int totalItems){
		if (totalItems<=0) {
			return 1;
		}
		return (int) Math.ceil(((double)totalItems)/SINGLE_PAGE_ITEMS);
	}
	
	
	public static class UploadingAdapter extends FragmentPagerAdapter {
		
		
		public UploadingAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			return ArrayListFragment.newInstance(position);
		}

		@Override
		public int getCount() {
			return totalPages;
		}
		
		public static class ArrayListFragment extends ListFragment {
			int mNum;
			static ArrayListFragment newInstance(int num){
				ArrayListFragment f=new ArrayListFragment();
				Bundle args=new Bundle();
				args.putInt("num", num);
				f.setArguments(args);
				return f;
			}
			
			@Override
			public void onCreate(Bundle savedInstanceState) {
				super.onCreate(savedInstanceState);
				mNum=getArguments()!=null?getArguments().getInt("num"):1;
			}
			
			@Override
			public View onCreateView(LayoutInflater inflater, ViewGroup container,
					Bundle savedInstanceState) {
				return inflater.inflate(R.layout.list_uploading, null);
			}
			
			@Override
			public void onActivityCreated(Bundle savedInstanceState) {
				super.onActivityCreated(savedInstanceState);
				List<Record> pageData = getPageData(mNum);
				setListAdapter(new SinglePageAdapter(getActivity(), pageData));
			}
			
			@Override
			public void onListItemClick(ListView l, View v, int position, long id) {
				super.onListItemClick(l, v, position, id);
			}
			
			public static List<Record> getPageData(int page){
				List<Record> data=new ArrayList<Record>();
				int startIndex=(int) (page*SINGLE_PAGE_ITEMS);
				int endIndex=(int) (startIndex+SINGLE_PAGE_ITEMS);
				if (endIndex>records.size()) {
					endIndex=records.size();
				}
				for(int i=startIndex;i<endIndex;i++){
					data.add(records.get(i));
				}
				return data;
			}
		}
		
		public static class SinglePageAdapter extends BaseAdapter{
			
			private List<Record> records;
			private LayoutInflater inflater;
			private int progressLength;
			private ImageView ivTotalTask;
			
			public SinglePageAdapter(Context context,List<Record> records){
				inflater = LayoutInflater.from(context);
				this.records=records;
			}
			public int getCount() {
				return records.size();
			}

			public Object getItem(int position) {
				return records.get(position);
			}

			public long getItemId(int position) {
				return position;
			}

			public View getView(int position, View convertView, ViewGroup parent) {
				View root = inflater.inflate(R.layout.item_uploading, null);
				TextView tvName=(TextView) root.findViewById(R.id.upload_filename);
				TextView tvDir=(TextView) root.findViewById(R.id.upload_dir);
				TextView tvPercent=(TextView) root.findViewById(R.id.upload_percent);
				ivTotalTask = (ImageView)root.findViewById(R.id.upload_progress_total);
				ImageView ivFinishedTask=(ImageView)root.findViewById(R.id.upload_progress_finished);
				Button btnCancel=(Button)root.findViewById(R.id.btn_cancel);
				Record record = records.get(position);
				
				tvName.setText(record.fileName);
				tvDir.setText(record.destDir);
				tvPercent.setText("已完成"+record.finishedSize+"%");
				if (progressLength>0) {
					if (ivTotalTask.getViewTreeObserver().isAlive()) {
						ivTotalTask.getViewTreeObserver().removeOnPreDrawListener(listener);
					}
					setWidth(ivFinishedTask, record);
				}else {
					ivTotalTask.getViewTreeObserver().addOnPreDrawListener(listener);
				}
				return root;
			}
			public void setWidth(ImageView ivFinishedTask, Record record) {
				if (ivFinishedTask!=null) {
					LayoutParams params = ivFinishedTask.getLayoutParams();
					params.width=record.finishedSize*progressLength/100;
					ivFinishedTask.setLayoutParams(params);
				}
			}
			OnPreDrawListener listener=new OnPreDrawListener() {
				public boolean onPreDraw() {
					progressLength=ivTotalTask.getMeasuredWidth();
					return true;
				}
			};
		}
	}
}
